import { ComponentFactoryResolver, Injectable, ReflectiveInjector, ViewContainerRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';

import { SiderComponentLoaderOptions } from '../models';
import { SideComponentContainerComponent } from '../components/side-component-container/side-component-container.component';

@Injectable()
export class SideComponentLoaderService {

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  show(options: SiderComponentLoaderOptions): Observable<any> {
    return Observable.create((observer: Observer<any>) => {
      const viewContainerRef: ViewContainerRef = options.viewContainerRef;
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(SideComponentContainerComponent);
      viewContainerRef.clear();
      const componentRef = viewContainerRef.createComponent(componentFactory);
      if(options.position === undefined) {
        options.position = 'right';
      }
      (<SideComponentContainerComponent>componentRef.instance).component = options.component;
      (<SideComponentContainerComponent>componentRef.instance).params = options.params || {};
      (<SideComponentContainerComponent>componentRef.instance).position = options.position;
      (<SideComponentContainerComponent>componentRef.instance).onChange.subscribe((data: any) => observer.next(data));
      (<SideComponentContainerComponent>componentRef.instance).onClose.subscribe(() => {
        observer.complete();
        viewContainerRef.clear();
      });
      (<SideComponentContainerComponent>componentRef.instance).onError.subscribe((data: any) => {
        viewContainerRef.clear();
        observer.error(data);
      });
    });
  }

}
